﻿using System.ComponentModel;
using System.Data.Entity;
using System.Web;
using Yz.Base.Dal;
using Yz.Model.Entities;

namespace Yz.Model.Dal
{
    [Description("YzFramework")]
    public class YzContext : DbContext
    {
        #region 数据库连接
        private static readonly string _conStr = DBConstant.YzConnStr;
        /// </summary>
        public YzContext()
            : base(_conStr)
        {
            Database.SetInitializer(new MigrateDBToLatestVersion<YzContext, Configuration>(_conStr));
        }
        /// <summary>
        /// 调用学年数据库
        /// </summary>
        /// <param name="connStr"></param>
        private YzContext(string connStr)
            : base(connStr)
        {
            Database.SetInitializer(new MigrateDBToLatestVersion<YzContext, Configuration>(connStr));
        }

        public static YzContext GetInstance(bool rOnly = false)
        {
            YzContext efDbContext = null;
            if (HttpContext.Current != null)
            {
                efDbContext = HttpContext.Current.Items[DBContextName.YzContext] as YzContext;
            }
            if (efDbContext == null || !DBConstant.IsConnStrHasPwd(efDbContext.Database.Connection.ConnectionString))
            {
                efDbContext = new YzContext(_conStr);
                //存入到这个线程缓存中
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Items[DBContextName.YzContext] = efDbContext;
                }
            }
            if (rOnly)//只读，提升性能
            {
                efDbContext.SetDbReadOnly();
            }
            return efDbContext;
        }
        #endregion

        #region 数据表
        /// <summary>
        /// 用户信息 
        /// </summary>
        [Description("用户信息")]
        public DbSet<User> Users { get; set; }
        /// <summary>
        /// 管理员信息 
        /// </summary>
        [Description("管理员信息")]
        public DbSet<Admin> Admins { get; set; }
        /// <summary>
        /// 分享码 
        /// </summary>
        [Description("分享码")]
        public DbSet<ShareCode> ShareCodes { get; set; }
        #endregion


        #region 增加数据库表字段限制
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

        }
        #endregion 
    }
}
